package user_v1

import (
	"context"
	"errors"
	"gf-xb-api/internal/consts"
	"gf-xb-api/internal/dao"
	"gf-xb-api/internal/model/dto"
	"gf-xb-api/internal/model/entity"
	"gf-xb-api/internal/service"
	"gf-xb-api/utility/xstr"

	"github.com/gogf/gf/v2/database/gdb"
)

func (s *sUser) ResetPassword(ctx context.Context, in dto.UserResetPasswordInput) (output bool, err error) {
	// 参数检查
	if in.NewPassword != in.RepeatPassword {
		return false, errors.New(consts.INVALID_NEW_REPEAT_PASSWORD)
	}

	if !xstr.IsValidPassword(in.NewPassword) {
		return false, errors.New(consts.INVALID_NEW_PASSWORD)
	}

	var user *entity.SysUser

	err = dao.SysUser.Ctx(ctx).Where(dao.SysUser.Columns().Username, in.Username).Scan(&user)
	if err != nil {
		return false, err
	}

	if user == nil {
		return false, errors.New(consts.USER_NOT_FOUND)
	}

	// 检查当前密码是否一致
	if !xstr.IsPasswordSame(user.PasswordHash, in.OldPassword) {
		return false, errors.New(consts.INVALID_OLD_PASSWORD)
	}

	// 新密码hash
	newPassword, err := xstr.GeneratePasswordHash(in.NewPassword)
	if err != nil {
		return false, err
	}

	dao.SysUser.Transaction(ctx, func(ctx context.Context, tx gdb.TX) (err error) {

		_, err = dao.SysUser.Ctx(ctx).Data(dao.SysUser.Columns().PasswordHash, newPassword).Where(dao.SysUser.Columns().Username, in.Username).Update()
		if err != nil {
			return err
		}

		// 将该用户的已登录实例强制登出
		err = service.User().LogoutByUuid(ctx, user.Uuid)
		if err != nil {
			return err
		}

		return
	})

	return true, nil
}
